package com.rongji.dfish.demo.editor.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rongji.dfish.base.Utils;
import com.rongji.dfish.demo.base.DemoBaseController;
import com.rongji.dfish.demo.constant.DemoConstants;
import com.rongji.dfish.demo.editor.service.EditorDirService;
import com.rongji.dfish.demo.editor.view.EditorCommonView;
import com.rongji.dfish.demo.editor.view.EditorDirView;
import com.rongji.dfish.demo.entity.DfishView;
import com.rongji.dfish.demo.entity.DfishViewDir;
import com.rongji.dfish.demo.entity.PubLoginUser;
import com.rongji.dfish.demo.index.service.AnchorHelper;
import com.rongji.dfish.demo.pub.service.UserService;
import com.rongji.dfish.demo.pub.view.PubView;
import com.rongji.dfish.framework.FrameworkHelper;
import com.rongji.dfish.ui.command.CommandGroup;
import com.rongji.dfish.ui.command.JSCommand;
import com.rongji.dfish.ui.command.MenuCommand;
import com.rongji.dfish.ui.command.ReplaceCommand;
import com.rongji.dfish.ui.layout.View;
import com.rongji.dfish.ui.widget.Leaf;

@Controller
@RequestMapping("/editorDir")
public class EditorDirController extends DemoBaseController {

	@Autowired
	private EditorDirService editorDirService;
	
	public EditorDirService getEditorDirService() {
		return editorDirService;
	}

	public void setEditorDirService(EditorDirService editorDirService) {
		this.editorDirService = editorDirService;
	}

	@RequestMapping("/index")
	@ResponseBody
	public Object index(HttpServletRequest request) throws Exception {
		View view = getIndexView(request);
		return view;
	}
	
	private View getIndexView(HttpServletRequest request) throws Exception {
		String loginUserId = FrameworkHelper.getLoginUser(request);
		String fromModule = request.getParameter("fromModule");
		String dirId = request.getParameter("dirId");
		String viewId = request.getParameter("viewId");
		if(Utils.isEmpty(dirId)){
			String anchor=request.getParameter("anchor");
			if(Utils.notEmpty(anchor)){
				String[] infos=AnchorHelper.getInstance().getAnchorInfo(anchor);
				if(infos!=null&&infos.length>2&&infos[1].equals("folder")){
					dirId=infos[2];
				}else if(infos!=null&&infos.length>2&&infos[1].equals("file")){
					viewId=infos[2];
					DfishView view=(DfishView) FrameworkHelper.getDAO().queryAsAnObject("FROM DfishView t WHERE t.viewId=?", viewId);
					if(view!=null){
						dirId=view.getViewDir();
					}
				}
			}
		}
		
		PubLoginUser loginUser = null;
		if (DemoConstants.MOD_EXAMPLE.equals(fromModule)) { // 模板
			loginUser = UserService.getAdminUser();
		} else {
			if (Utils.isEmpty(loginUserId)) { // 无登录,游客身份
				loginUser = UserService.getGuestUser();
			} else { // 正常登录用户
				// do nothing
			}
		}
		if (loginUser != null) {
			loginUserId = loginUser.getUserId();
		}
		
		DfishViewDir targetDir = null;
		if (Utils.isEmpty(dirId) || DemoConstants.ID_ROOT.equals(dirId) || dirId.startsWith(DemoConstants.ITEM_USER)) {
			targetDir = EditorCommonView.getRootDir(loginUserId);
		} else {
			targetDir = editorDirService.getViewDir(dirId);
		}
		
//		List<DfishViewDir> subDirs = null;
//		List<DfishView> subViews = null;
//		if (Utils.isEmpty(dirId) || DemoConstants.ID_ROOT.equals(dirId)) {
//			subDirs = editorDirService.findRootDirs(loginUserId);
//			subViews = new ArrayList<DfishView>(0);
//		} else if (dirId.startsWith(DemoConstants.DIR_PRE_USER)) {
//			String dirCreator = dirId.substring(2);
//			subDirs = editorDirService.findRootDirs(dirCreator);
//			subViews = editorDirService.findViews(dirCreator);
//			targetDir = EditorCommonView.getRootDir(dirCreator);
//		} else {
//			subDirs = editorDirService.findSubDirs(dirId);
//			subViews = editorDirService.findViews(dirId);
//			targetDir = editorDirService.getViewDir(dirId);
//		}
		
		Map<String, List<DfishViewDir>> dirMap = new HashMap<String, List<DfishViewDir>>();
		Map<String, List<DfishView>> viewMap = new HashMap<String, List<DfishView>>();
		fillPathData(dirMap, viewMap, targetDir, fromModule);
		View view = EditorDirView.buildIndexView(targetDir,viewId, dirMap, viewMap, fromModule);
		return view;
	}
	
	private Map<String, List<DfishViewDir>> fillPathData(Map<String, List<DfishViewDir>> dirMap, Map<String, List<DfishView>> viewMap, DfishViewDir targetDir, String fromModule) {
		// 全部在前端显示,前端的性能可能撑不住
		String dirCreator = targetDir.getDirCreator();
		
		fillDirData(dirMap, dirCreator);
		fillViewData(viewMap, dirCreator);
		
		if (!DemoConstants.USER_GUEST.equals(dirCreator) && DemoConstants.MOD_EXPERIENCE.equals(fromModule)) { // 在线编辑模块时需加入游客目录
			fillDirData(dirMap, DemoConstants.USER_GUEST);
			fillViewData(viewMap, DemoConstants.USER_GUEST);
		}
		
		return dirMap;
	}
	
	private void fillDirData(Map<String, List<DfishViewDir>> dirMap, String dirCreator) {
		// FIXME 一次性取的太多目录,可能要改造成按需获取
		List<DfishViewDir> dirList = editorDirService.findDirs(dirCreator);
		
		String userDirId = DemoConstants.ITEM_USER + dirCreator;
		for (DfishViewDir dir : dirList) {
			String pId = dir.getDirParent();
			if (Utils.isEmpty(pId) || DemoConstants.ID_ROOT.equals(pId)) {
				// 根目录
				pId = userDirId;
			}
			List<DfishViewDir> subList = dirMap.get(pId);
			if (subList == null) {
				subList = new ArrayList<DfishViewDir>();
				dirMap.put(pId, subList);
			}
			subList.add(dir);
		}
		
		// 加入到根节点去
		String treeRoot = DemoConstants.TREE_ROOT;
		List<DfishViewDir> subList = dirMap.get(treeRoot);
		if (subList == null) {
			subList = new ArrayList<DfishViewDir>();
			dirMap.put(treeRoot, subList);
		}
		subList.add(EditorDirView.getRootDir(dirCreator));
	}
	
	
	private void fillViewData(Map<String, List<DfishView>> viewMap, String dirCreator) {
		List<DfishView> viewList = editorDirService.findAllViews(dirCreator);
		for (DfishView view : viewList) {
			List<DfishView> subList = viewMap.get(view.getViewDir());
			if (subList == null) {
				subList = new ArrayList<DfishView>();
				viewMap.put(view.getViewDir(), subList);
			}
			subList.add(view);
		}
	}
	
	@RequestMapping("/enterDir")
	@ResponseBody
	public Object enterDir(HttpServletRequest request) throws Exception {
		// FIXME 这里构建左边树的代码需要去除
		View view = getIndexView(request);
		CommandGroup cg = new CommandGroup();
		cg.add(new ReplaceCommand(view.findNodeById(PubView.MAIN_ROOT)));
		String dirId = request.getParameter("dirId");
		cg.add(new JSCommand("VM(this).data('targetDir','"+dirId+"')"));
		return cg;
	}
	
	@RequestMapping("/openTo")
	@ResponseBody
	public Object openTo(HttpServletRequest request) throws Exception {
		Leaf leaf = new Leaf();
		return leaf;
	}
	
	@RequestMapping("/edit")
	@ResponseBody
	public Object edit(HttpServletRequest request) throws Exception {
		String editId = request.getParameter("editId");
		String editType = request.getParameter("editType");
		String targetDir = request.getParameter("targetDir");
		String fromModule = request.getParameter("fromModule");

		DfishViewDir toDir = null;
		String dirParent = null;
		String dirCreator = null;
		if (Utils.isEmpty(targetDir)) {
			// 理论上应该不会出现这种情况,暂时不处理
		} else if (targetDir.startsWith(DemoConstants.ITEM_USER)) {
			dirParent = DemoConstants.ID_ROOT;
			dirCreator = targetDir.substring(DemoConstants.ITEM_USER.length());
		} else {
			toDir = editorDirService.get(targetDir);
			dirParent = toDir.getDirId();
			dirCreator = toDir.getDirCreator();
		}
		View view = null;
		boolean readonly = !DemoConstants.MOD_EXPERIENCE.equals(fromModule);
		if (DemoConstants.ITEM_FILE.equals(editType)) { // 编辑视图
			DfishView dView = null;
			if (Utils.notEmpty(editId)) {
				dView = editorDirService.getView(editId);
			}
			
			if (dView == null) {
				dView = new DfishView();
				dView.setViewDir(dirParent);
				dView.setViewCreator(dirCreator);
				dView.setViewOrder(editorDirService.getViewNewOrder(dirParent, dirCreator));
				dView.setViewVersion(1L);
			}
			view = EditorDirView.buildViewEditView(dView, readonly);
		} else { // 编辑目录
			DfishViewDir viewDir = null;
			if (Utils.notEmpty(editId)) {
				viewDir = editorDirService.getViewDir(editId);
			}
			if (viewDir == null) {
				viewDir = new DfishViewDir();
				
				viewDir.setDirParent(dirParent);
				viewDir.setDirCreator(dirCreator);
				viewDir.setDirOrder(editorDirService.getDirNewOrder(dirParent, dirCreator));
			}
			view = EditorDirView.buildDirEditView(viewDir, readonly);
		}
		return view;
	}
	
	/**
	 * 点击后，菜单功能
	 * @return Object
	 * @throws Exception
	 */
	@RequestMapping("/itemMenu")
	@ResponseBody
	public Object itemMenu(HttpServletRequest request) throws Exception {
		String itemId = request.getParameter("itemId");
		String itemType = request.getParameter("itemType");
		String posIndexStr = request.getParameter("posIndex");
		int posIndex = Integer.parseInt(posIndexStr);
		
		String fromModule = request.getParameter("fromModule");
		MenuCommand menu = EditorDirView.buildItemMenu(itemId, itemType, posIndex, fromModule);
		return menu;
	}
	
	/**
	 * 右上角视图控制
	 * @param dirId
	 * @param category
	 * @return Object
	 * @throws Exception
	 */
	@RequestMapping("/dirMenu")
	@ResponseBody
	public Object dirMenu(HttpServletRequest request) throws Exception {
		String targetDir = request.getParameter("targetDir");
		
		HttpSession session = request.getSession();
		String copyItemId = (String) session.getAttribute("copyItemId");
		MenuCommand menu = EditorDirView.buildDirMenu(targetDir, Utils.notEmpty(copyItemId));
		return menu;
	}
	
	@RequestMapping("/saveView")
	@ResponseBody
	public Object saveView(HttpServletRequest request) throws Exception {
		DfishView dView = new DfishView();
		bind(request, dView);

		if (Utils.isEmpty(dView.getViewId())) {
			editorDirService.save(dView);
		} else {
			editorDirService.update(dView);
		}
		
		String itemId = dView.getViewDir();
		String itemType = DemoConstants.ITEM_DIR;
		if (DemoConstants.ID_ROOT.equals(itemId)) {
			itemId = DemoConstants.ITEM_USER + dView.getViewCreator();
			itemType = DemoConstants.ITEM_USER;
		}
		CommandGroup cg = new CommandGroup();
		cg.add(PubView.getAlertInfo("保存成功"));
		cg.add(new JSCommand("var d=$.dialog(this);editor.dir.enter(d.ownerView, '"+itemId+"','"+itemType+"');d.close();"));
		return cg;
	}
	
	@RequestMapping("/saveDir")
	@ResponseBody
	public Object saveDir(HttpServletRequest request) throws Exception {
		DfishViewDir viewDir = new DfishViewDir();
		bind(request, viewDir);
		
		if (Utils.isEmpty(viewDir.getDirId())) {
			editorDirService.save(viewDir);
		} else {
			editorDirService.update(viewDir);
		}
		String itemId = viewDir.getDirParent();
		String itemType = DemoConstants.ITEM_DIR;
		if (DemoConstants.ID_ROOT.equals(itemId)) {
			itemId = DemoConstants.ITEM_USER + viewDir.getDirCreator();
			itemType = DemoConstants.ITEM_USER;
		}
		// FIXME 左边导航栏的需要更新
		CommandGroup cg = new CommandGroup();
		cg.add(PubView.getAlertInfo("保存成功"));
		cg.add(new JSCommand("var d=$.dialog(this);editor.dir.enterDir(d.ownerView, '"+itemId+"');d.close();"));
		return cg;
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(HttpServletRequest request) throws Exception {
		
		String selectItem = request.getParameter("selectItem");
		String targetDir = request.getParameter("targetDir");
		
		String[] delArray = selectItem.split(",");
		// 
		Set<String> dirs = new HashSet<String>();
		Set<String> editors = new HashSet<String>();
		for (String item : delArray) {
			if (item.startsWith(DemoConstants.ITEM_DIR)) {
				dirs.add(item.substring(DemoConstants.ITEM_DIR.length()));
			} else if (item.startsWith(DemoConstants.ITEM_FILE)) {
				editors.add(item.substring(DemoConstants.ITEM_FILE.length()));
			}
		}
		// FIXME 删除前判断是否含有子目录和子文件
		for (String item : dirs) {
			editorDirService.deleteCascade(item, DemoConstants.ITEM_DIR);
		}
		for (String item : editors) {
			editorDirService.deleteCascade(item, DemoConstants.ITEM_FILE);
		}
		
//		String id = request.getParameter("id");
//		String type = request.getParameter("type");
//		String pDir = request.getParameter("pDir");
//		String category = request.getParameter("category");
//		editorDirService.deleteCascade(id, type);
//		return new JSCommand("editor.dir.enterDir(this,'" + pDir + "','" + category + "');this.find('" + id + "').remove();");
		CommandGroup cg = new CommandGroup();
		cg.add(PubView.getAlertInfo("删除成功"));
		StringBuilder js = new StringBuilder();
		js.append("editor.dir.enterDir(this,'").append(targetDir).append("','0');");
		for (String item : dirs) {
			js.append("VM(this).find('").append(item).append("').remove();");
		}
		cg.add(new JSCommand(js.toString()));
		return cg;
	}
	
	@RequestMapping("/copyItem")
	@ResponseBody
	public Object copyItem(HttpServletRequest request) throws Exception {
		String itemId = request.getParameter("itemId");
		String itemType = request.getParameter("itemType");
		String copyType = request.getParameter("copyType");
		HttpSession session = request.getSession();
		session.setAttribute("copyItemId", itemId);
		session.setAttribute("copyItemType", itemType);
		session.setAttribute("copyType", copyType);
		return PubView.getAlertInfo("粘贴板已更新");
	}
	
	@RequestMapping("/pasteItem")
	@ResponseBody
	public Object pasteItem(HttpServletRequest request) throws Exception {
		// 肯定是目录,无需再进行判断
		String toDir = request.getParameter("toDir");
		
		HttpSession session = request.getSession();
		String copyItemId = (String) session.getAttribute("copyItemId");
		String copyItemType = (String) session.getAttribute("copyItemType");
		String copyType = (String) session.getAttribute("copyType");
		
		if (DemoConstants.OPER_CUT.equals(copyType)) { // 剪切
			if (toDir.startsWith(DemoConstants.ITEM_USER)) {
				toDir = DemoConstants.ID_ROOT;
			}
			if (DemoConstants.ITEM_FILE.equals(copyItemType) && DemoConstants.ID_ROOT.equals(toDir)) {
				// 文件不允许移到根目录
				return PubView.getAlertWarn("不支持文件移动到根目录");
			}
			editorDirService.move2NewDir(copyItemId, copyItemType, toDir);
		} else { // 复制  
			DfishView dView = editorDirService.getView(copyItemId);
			if (dView == null) {
				FrameworkHelper.LOG.warn("找不到视图[" + copyItemId + "]");
				return PubView.getAlertInfo("粘贴过程异常,请联系管理员["+copyItemId+"]");
			}
			dView.setViewName(dView.getViewName()+"_副本");
			dView.setViewDir(toDir);
			editorDirService.copyTo(dView, copyItemId);
		}
		
		CommandGroup cg = new CommandGroup();
		
		cg.add(PubView.getAlertInfo("粘贴成功"));
		return cg;
	}
	
	@RequestMapping("/move")
	@ResponseBody
	public Object move(HttpServletRequest request) throws Exception {
		String itemId = request.getParameter("itemId");
		String itemType = request.getParameter("itemType");
		String moveType = request.getParameter("moveType");
		// FIXME 暂且支持单个目录或者文件移动,暂不支持批量移动
		if (DemoConstants.ITEM_FILE.equals(itemType)) {
			editorDirService.moveView(itemId, moveType);
		} else {
			editorDirService.moveDir(itemId, moveType);
		}
		return new JSCommand("editor.dir.enterDir(this,VM(this).data('targetDir'));");
	}
	
	@RequestMapping("/moveTo")
	@ResponseBody
	public Object moveTo(HttpServletRequest request) throws Exception {
		// FIXME 暂且支持单个目录或者文件移动,暂不支持批量移动
		String itemId = request.getParameter("itemId");
		String itemType = request.getParameter("itemType");
		String fromDir = request.getParameter("fromDir");
		String dirCreator = "";
		DfishViewDir pDir = null;
		if (fromDir.startsWith(DemoConstants.ITEM_USER)) {
			dirCreator = fromDir.substring(DemoConstants.ITEM_USER.length());
			pDir = EditorCommonView.getRootDir(dirCreator);
		} else {
			pDir = editorDirService.get(fromDir);
		}
		dirCreator = pDir.getDirCreator();
		
		List<DfishViewDir> dirList = editorDirService.findDirs(dirCreator);
		View view = EditorDirView.buildMoveToView(dirList, itemId, itemType, pDir);
		return view;
	}
	
	@RequestMapping("/doMove")
	@ResponseBody
	public Object doMove(HttpServletRequest request) throws Exception {
		String itemId = request.getParameter("itemId");
		String itemType = request.getParameter("itemType");
		String fromDir = request.getParameter("fromDir");
		String toDir = request.getParameter("toDir");
		
		if (toDir.startsWith(DemoConstants.ITEM_USER)) {
			toDir = toDir.substring(DemoConstants.ITEM_USER.length());
		}
		editorDirService.move2NewDir(itemId, itemType, toDir);
//		return new JSCommand("var d=$.dialog(this);editor.dir.enterDir(d.ownerView,'" + pDir + "','" + category + "');" 
//							+"d.ownerView.find('" + id + "').remove();"
//							+"d.ownerView.find('" + targetDir + "').reload();d.close();");
		CommandGroup cg = new CommandGroup();
		cg.add(new JSCommand("editor.dir.enterDir(this.ownerView.parent, '" + fromDir + "');$.close(this);"));
		return cg;
	}
	
	@RequestMapping("/copyTo")
	@ResponseBody
	public Object copyTo(HttpServletRequest request) throws Exception {
		String itemId = request.getParameter("itemId");
		// 仅支持文件的复制
		DfishView dView = editorDirService.getView(itemId);
		dView.setViewName(dView.getViewName() + "_副本");
		View view = EditorDirView.buildViewEditView(dView, true);
		return view;
	}
	
	@RequestMapping("/copySelect")
	@ResponseBody
	public Object copySelect(HttpServletRequest request) throws Exception {
		String itemId = request.getParameter("itemId");
		String fromDir = request.getParameter("fromDir");
		String loginUserId = FrameworkHelper.getLoginUser(request);
		List<String> dirCreators = new ArrayList<String>();
		if (Utils.notEmpty(loginUserId)) {
			dirCreators.add(loginUserId);
		}
		DfishViewDir pDir = editorDirService.get(fromDir);
		if (!dirCreators.contains(pDir.getDirCreator())) {
			dirCreators.add(pDir.getDirCreator());
		}
		List<DfishViewDir> dirList = new ArrayList<DfishViewDir>();
		for (String dirCreator : dirCreators) {
			List<DfishViewDir> tempList = editorDirService.findDirs(dirCreator);
			dirList.addAll(tempList);
		}
		// 目前仅支持文件的复制
		View view = EditorDirView.buildCopySelectView(dirList, itemId, DemoConstants.ITEM_FILE, pDir);
		return view;
	}
	
	@RequestMapping("/dirCandidate")
	@ResponseBody
	public Object dirCandidate(HttpServletRequest request) throws Exception {
		String dirId = request.getParameter("dirId");
		DfishViewDir dir = editorDirService.get(dirId);
		List<Object[]> dataList = new ArrayList<Object[]>();
		dataList.add(new Object[]{ dir.getDirId(), dir.getDirName() });
		View view = PubView.buildCandidateView(dataList);
		return view;
	}
	
	@RequestMapping("/doCopy")
	@ResponseBody
	public Object doCopy(HttpServletRequest request) throws Exception {
		DfishView dView = new DfishView();
		bind(request, dView);
		
		String oldViewId = request.getParameter("oldViewId");
		editorDirService.copyTo(dView, oldViewId);
		CommandGroup cg = new CommandGroup();
		cg.add(PubView.getAlertInfo("复制成功"));
		cg.add(new JSCommand("$.close(this);"));
		return cg;
	}
	
	@RequestMapping("/reorder")
	@ResponseBody
	public Object reorder(HttpServletRequest request) throws Exception {
		String dirId = request.getParameter("dirId");
		String orderType = request.getParameter("orderType");
		editorDirService.reorder(dirId, orderType);
		return new JSCommand("editor.dir.enterDir(this,'" + dirId + "');");
	}
	
	@RequestMapping("/open/{dirId}")
	@ResponseBody
	public Object open(@PathVariable String dirId) throws Exception {
		String category="";
		if(dirId.startsWith("ROOT_")){
			category=dirId.substring(5);
			dirId = DemoConstants.ID_ROOT;
		}

		List<DfishViewDir> dirs = editorDirService.findSubDirs(dirId);
		List<DfishView> subViews = editorDirService.findViews( dirId);
		Leaf shell=new Leaf();

		int i=0;
		for(DfishViewDir dir:dirs){
			int posType =0;
			if (i == 0) {
				if((i + 1) != dirs.size()) {
					posType = -1;
				} else {
					posType = -2;	
				}
			} else if ((i + 1) == dirs.size()) {
				posType = 1;
			}
			i++;
			Leaf leaf=new Leaf();
			shell.add(leaf);
			leaf.setId(dir.getDirId());
			leaf.setText(dir.getDirName());
			leaf.setSrc("editorDir/open/"+dir.getDirId());
			leaf.setIcon(".ico-folder-open");
			leaf.setOn(Leaf.EVENT_CLICK, "editor.dir.enterDir(this, '" + dir.getDirId() + "', '" + dir.getDirCreator() + "');");
			leaf.setOn(Leaf.EVENT_CONTEXTMENU, "editor.dir.itemMenu(this,'"+dir.getDirId()+"','"+DemoConstants.ITEM_DIR+"','"+dir.getDirParent()+"','"+category+"','"+posType+"');");
			
		}
		i=0;
		for(DfishView view:subViews){
			int posType =0;
			if (i == 0) {
				if((i + 1) != subViews.size()) {
					posType = -1;
				} else {
					posType = -2;	
				}
			} else if ((i + 1) == subViews.size()) {
				posType = 1;
			}
			
			i++;
			Leaf leaf=new Leaf();
			shell.add(leaf);
			leaf.setId(view.getViewId());
			leaf.setText(view.getViewName());
			leaf.setOn(Leaf.EVENT_CLICK, "editor.dir.enterEditor(this, '" + view.getViewId() + "');");
			leaf.setOn(Leaf.EVENT_CONTEXTMENU, "editor.dir.itemMenu(this,'"+view.getViewId()+"','"+DemoConstants.ITEM_FILE+"','"+view.getViewDir()+"','"+category+"','"+posType+"');");
		}
		return shell;
	}
}
